//
//  MSKeyBoardTool.m
//  PeopleForTheFirstMall
//
//  Created by mac on 2021/5/31.
//  Copyright © 2021 MS. All rights reserved.
//

#import "MSKeyBoardTool.h"
#import "MSMacro.h"
#import <ReactiveObjC/ReactiveObjC.h>

@interface MSKeyBoardTool ()

@property (nonatomic, strong) id        currentTextField;
@property (nonatomic, strong) UIView    *animationView;

@end

@implementation MSKeyBoardTool


#pragma mark - public method
/** 键盘遮挡自动上移（注：键盘弹出前调用，如textFieldDidBeginEditing:代理方法） */
- (void)ms_autoMoveTextFieldUp:(id)textField
                 animationView:(UIView *)animationView
                   showToolBar:(BOOL)showToolBar
{
    if (![textField isKindOfClass:[UITextField class]] &&
        ![textField isKindOfClass:[UITextView class]] &&
        ![textField isKindOfClass:[YYTextView class]])
    {
        return;
    }
    self.currentTextField = textField;
    self.animationView = animationView;
    
    if (showToolBar)
    {
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace)
                                                                                   target:self
                                                                                   action:nil];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
        titleLabel.textColor = MS_HEX_COLOR(0x444444);
        titleLabel.font = MS_SYSTEM_FONT_OF_SIZE(13);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = [textField respondsToSelector:@selector(placeholderText)] ? [textField placeholderText] : [textField placeholder];
        
        UIBarButtonItem *titleItem = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
        UIBarButtonItem *doneItem = [[UIBarButtonItem alloc]initWithTitle:@"完成"
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector(done)];
        doneItem.tintColor = UIColor.blueColor;
        if (!ms_arrayIsEmpty(self.fieldArray) && self.fieldArray.count > 1)
        {
            UIImage *img = [MS_IMAGE_NAMED(@"back") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            UIImage *lastImg = [UIImage imageWithCGImage:img.CGImage
                                                   scale:img.scale
                                             orientation:UIImageOrientationRight];
            UIImage *nextImg = [UIImage imageWithCGImage:img.CGImage
                                                   scale:img.scale
                                             orientation:UIImageOrientationLeft];
            UIButton *lastBtn = [[UIButton alloc] init];
            lastBtn.tintAdjustmentMode = UIViewTintAdjustmentModeAutomatic;
            [lastBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
                
                make
                .ms_frame(0, 0, 35, 44)
                .ms_image([lastImg imageChangeColor:UIColor.blueColor], UIControlStateNormal)
                .ms_tintColor(UIColor.blueColor)
                .ms_addTarget(self, @selector(changePrevious));
            }];
            UIButton *nextBtn = UIButton.new;
            [nextBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
                
                make
                .ms_frame(0, 0, 35, 44)
                .ms_image([nextImg imageChangeColor:UIColor.blueColor], UIControlStateNormal)
                .ms_tintColor(UIColor.blueColor)
                .ms_addTarget(self, @selector(changeNext));
            }];
            
            UIBarButtonItem *previousItem = [[UIBarButtonItem alloc] initWithCustomView:lastBtn];
            [previousItem setTintColor:UIColor.blueColor];
            UIBarButtonItem *nextItem = [[UIBarButtonItem alloc] initWithCustomView:nextBtn];
            [nextItem setTintColor:UIColor.blueColor];
            
            self.toolBar.items = @[previousItem, nextItem, spaceItem, titleItem, spaceItem, doneItem];
            
            NSInteger current = [self.fieldArray indexOfObject:self.currentTextField];
            
            if (current == 0)
            {
                [self enableItemPrevious];
            }
            if (current == self.fieldArray.count - 1)
            {
                [self enableItemNext];
            }
            if (current != 0 && current != self.fieldArray.count - 1)
            {
                [self ableItemNext];
                [self ableItemPrevious];
            }
        }
        else
        {
            self.toolBar.items = @[spaceItem, titleItem, spaceItem, doneItem];
        }
        
        if ([textField isKindOfClass:[UITextField class]])
        {
            ((UITextField *)textField).inputAccessoryView = self.toolBar;
        }
        else if ([textField isKindOfClass:[UITextView class]])
        {
            ((UITextView *)textField).inputAccessoryView = self.toolBar;
        }
        else if ([textField isKindOfClass:[YYTextView class]])
        {
            ((YYTextView *)textField).inputAccessoryView = self.toolBar;
        }
    }
}
/** 每次切换输入框都会调用 */
- (void)showToolBar:(id)textField
      animationView:(UIView *)animationView
{
    self.currentTextField = textField;
    self.animationView = animationView;
}
/** 键盘遮挡自动上移 */
- (void)ms_animationOfTextField:(id)textField
                  animationView:(UIView *)animationView
{
    self.currentTextField = textField;
    self.animationView = animationView;
}


#pragma mark - event
/** 上一个 */
-(void)changePrevious
{
    NSInteger current = [self.fieldArray indexOfObject:self.currentTextField];

    if (current > 0)
    {
        id filed = [self.fieldArray objectAtIndex:current-1];
        if ([filed canBecomeFirstResponder])
        {
            [filed becomeFirstResponder];
        }
        
        [self ableItemNext];
        if (current-1 == 0)
        {
            [self enableItemPrevious];
            return;
        }
        else
        {
            [self ableItemPrevious];
            return;
        }
    }
}
/** 下一个 */
-(void)changeNext
{
    NSInteger current = [self.fieldArray indexOfObject:self.currentTextField];
    
    if (current+1 < self.fieldArray.count)
    {
        id filed = [self.fieldArray objectAtIndex:current+1];
        if ([filed canBecomeFirstResponder])
        {
            [filed becomeFirstResponder];
        }
        
        [self ableItemPrevious];
        if (current+1 == self.fieldArray.count-1)
        {
            [self enableItemNext];
            return;
        }
        else
        {
            [self ableItemNext];
            return;
        }
    }
}
/** 完成 */
-(void)done
{
    if ([self.currentTextField canResignFirstResponder])
    {
        [self.currentTextField resignFirstResponder];
    }
    
    if ([self.delegate respondsToSelector:@selector(ms_textFieldShouldReturn:)])
    {
        [self.delegate ms_textFieldShouldReturn:self.currentTextField];
    }
}


#pragma mark - 键盘遮挡自动上移
/** 键盘将要出现 */
- (void)keyboardWillShow:(NSNotification *)notification
{
    if (!self.animationView) return;
    /// 焦点视图
    UIView *focusView = nil;
    
    if ([self.currentTextField isFirstResponder])
    {
        focusView = self.currentTextField;
    }
    
    NSDictionary *userInfo = [notification userInfo];
    
    if (focusView)
    {
        //获取键盘弹出的时间
        double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //获取键盘上端Y坐标
        CGFloat keyboardY = [self getKeyboardY:userInfo];
        //获取输入框下端相对于window的Y坐标
        CGPoint tmp = [self getViewOriginPointToWindow:focusView];
        CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
        //计算二者差值
        CGFloat ty = keyboardY - inputBoxY;
        MSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
        //差值小于0，做平移变换
        [UIView animateWithDuration:duration animations:^{
            
            if (ty < 0)
            {
                self.animationView.transform = CGAffineTransformMakeTranslation(0, ty);
            }
        }];
    }
}
/** 键盘将要消失 */
- (void)keyboardWillHide:(NSNotification *)notification
{
    if (!self.animationView) return;
    NSDictionary *userInfo = [notification userInfo];
    //获取键盘弹出的时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //还原
    [UIView animateWithDuration:duration animations:^{
        
        self.animationView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}


#pragma mark - privace method
/** 上一个按钮不可点击 */
-(void)enableItemPrevious
{
    UIBarButtonItem *item = self.toolBar.items[0];
    [item setTintColor:[UIColor grayColor]];
    item.enabled = NO;
}
/** 上一个按钮可以点击 */
-(void)ableItemPrevious
{
    UIBarButtonItem *item = self.toolBar.items[0];
    [item setTintColor:[UIColor blueColor]];
    item.enabled = YES;
}
/** 下一个按钮不可点击 */
-(void)enableItemNext
{
    UIBarButtonItem *item = self.toolBar.items[1];
    [item setTintColor:[UIColor grayColor]];
    item.enabled = NO;
}
/** 下一个按钮可以点击 */
-(void)ableItemNext
{
    UIBarButtonItem *item = self.toolBar.items[1];
    [item setTintColor:[UIColor blueColor]];
    item.enabled = YES;
}

- (CGFloat)getKeyboardY:(NSDictionary *)userInfo
{
    CGFloat screenHeight;
    CGFloat keyboardY = 0;
    CGFloat keyboardHeight = 0;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if (([[[UIDevice currentDevice] systemVersion] floatValue] < 8) && UIInterfaceOrientationIsLandscape(orientation))
    {
        screenHeight = [[UIScreen mainScreen] bounds].size.width;
        keyboardHeight = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.width;
        keyboardY = screenHeight - keyboardHeight;
    }
    else if (([[[UIDevice currentDevice] systemVersion] floatValue] < 8) && UIInterfaceOrientationIsPortrait(orientation))
    {
        screenHeight = [[UIScreen mainScreen] bounds].size.height;
        keyboardHeight = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        keyboardY = screenHeight - keyboardHeight;
    }
    else
    {
        keyboardY = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    }
    
    return keyboardY;
}

- (CGPoint)getViewOriginPointToWindow:(UIView *)view
{
    CGPoint origin;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8)
    {
        CGPoint focusViewPoint = [view convertPoint:CGPointZero toView:nil];
        UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
        
        if (orientation == UIInterfaceOrientationLandscapeLeft)
        {
            origin.y = focusViewPoint.x;
            origin.x = [[[UIApplication sharedApplication] delegate] window].bounds.size.height - focusViewPoint.y;
        }
        else if (orientation == UIInterfaceOrientationLandscapeRight)
        {
            origin.y = [[[UIApplication sharedApplication] delegate] window].bounds.size.width - focusViewPoint.x;
            origin.x = focusViewPoint.y;
        }
        else if (orientation == UIInterfaceOrientationPortraitUpsideDown)
        {
            origin.y = [[[UIApplication sharedApplication] delegate] window].bounds.size.height - focusViewPoint.y;
            origin.x = [[[UIApplication sharedApplication] delegate] window].bounds.size.width - focusViewPoint.x;
        }
        else
        {
            origin = focusViewPoint;
        }
    }
    else
    {
        CGRect rect = [view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
        origin = rect.origin;
    }
    
    return origin;
}


- (instancetype)init
{
    if (self = [super init])
    {
        self.fieldArray = [NSArray array];
        self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, MS_SCREEN_WIDTH, 44)];
        UIBarButtonItem *flexibleSpace =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                               target:self
                                                                               action:nil];
        UIBarButtonItem *doneItem = [[UIBarButtonItem alloc]initWithTitle:@"完成"
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector(done)];
        self.toolBar.items = @[flexibleSpace, doneItem];
        
        ms_addObserver(self, @selector(keyboardWillShow:), UIKeyboardWillShowNotification, nil);
        ms_addObserver(self, @selector(keyboardWillHide:), UIKeyboardWillHideNotification, nil);
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
